{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 软投票和硬投票"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入相关的包"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.ensemble import VotingClassifier\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 实验数据\n",
    "\n",
    "from sklearn.datasets import load_breast_cancer\n",
    "\n",
    "bc = load_breast_cancer()\n",
    "y = bc.target\n",
    "X = pd.DataFrame.from_records(data=bc.data, columns=bc.feature_names)\n",
    "\n",
    "# 转化为df\n",
    "df = X\n",
    "df['target'] = y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 只取前3个特征\n",
    "cols = [\n",
    "    'mean radius',\n",
    "    'mean texture',\n",
    "    'mean perimeter',\n",
    "]\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(X[cols],\n",
    "                                                    y,\n",
    "                                                    test_size=0.3,\n",
    "                                                    random_state=42,\n",
    "                                                    stratify=y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "clf1 = KNeighborsClassifier(n_neighbors=1)\n",
    "\n",
    "clf2 = LogisticRegression(solver='liblinear', C=0.05, random_state=42)\n",
    "\n",
    "clf3 = DecisionTreeClassifier(max_depth=1, random_state=42)\n",
    "\n",
    "pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]])\n",
    "pipe2 = Pipeline([['sc', StandardScaler()], ['clf', clf2]])\n",
    "\n",
    "clf_labels = [\n",
    "    'KNN',\n",
    "    'Logistic',\n",
    "    'Decision tree',\n",
    "]\n",
    "\n",
    "voter = VotingClassifier(estimators=[('knn', pipe1), ('lr', pipe2),\n",
    "                                     ('dc', clf3)],\n",
    "                         voting='soft',\n",
    "                         weights=[1, 1, 1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "AUC:0.87 (+/- 0.035) [KNN]\n",
      "AUC:0.95 (+/- 0.031) [Logistic]\n",
      "AUC:0.86 (+/- 0.049) [Decision tree]\n",
      "AUC:0.95 (+/- 0.024) [Soft Voting]\n"
     ]
    }
   ],
   "source": [
    "for clf, label in zip([pipe1, pipe2, clf3, voter],\n",
    "                      clf_labels + ['Soft Voting']):\n",
    "    scores = cross_val_score(estimator=clf,\n",
    "                             X=X_train,\n",
    "                             y=y_train,\n",
    "                             cv=10,\n",
    "                             scoring='roc_auc')\n",
    "    print(\"AUC:{:.2} (+/- {:.2}) [{}]\".format(scores.mean(), scores.std(),\n",
    "                                              label))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
